package com.pateo.bjev.contacts.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.PopupMenuCompat;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.transition.TransitionManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.pateo.bjev.contacts.BjevContactsManager;
import com.pateo.bjev.contacts.MainActivity;
import com.pateo.bjev.contacts.R;
import com.pateo.bjev.contacts.adapter.CallItemDecoration;
import com.pateo.bjev.contacts.adapter.KeyGridAdapter;
import com.pateo.bjev.contacts.adapter.SearchNumAdapter;
import com.pateo.bjev.contacts.callback.ItemClickCallback;
import com.pateo.bjev.contacts.utils.CallUtils;
import com.pateo.bjev.contacts.utils.ContactSearchUtils;
import com.pateo.bluetooth.logic.bean.ContactData;

import java.util.LinkedList;
import java.util.List;

/**
 * 拨号盘 fragment
 * Created by pateo on 17-5-9.
 */

public class TwelveKeyFragment extends Fragment implements KeyGridAdapter.KeyInputCallback,
        View.OnClickListener,
        ContactSearchUtils.SearchCallback<ContactSearchUtils.SearchNumResult>,
        ItemClickCallback<ContactSearchUtils.SearchNumResult>
{

    View contentView;

    RecyclerView keyView;
    View call_btn;
    EditText numInput;
    View backspace;
    View searchResultView;
    TextView searchOneName,searchOneNum;

    BjevContactsManager manager;

    List<ContactData> contacts = new LinkedList<>();
    List<ContactSearchUtils.SearchNumResult> searchNumResults = new LinkedList<>();
    ContactSearchUtils.SearchNumResult searchOneTop;
    ContactSearchUtils<ContactSearchUtils.SearchNumResult> searchUtils;

    /**
     * 搜索到号码之后，点击第一条弹出的所有匹配联系人列表
     */
    PopupWindow searchList;
    RecyclerView search_list_view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = inflater.inflate(R.layout.twelvekey_layout,null);
        initView();
        return contentView;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if(context instanceof MainActivity){
            manager = ((MainActivity) context).getManager();
            try {
                contacts = manager.getContacts();
                searchUtils = new ContactSearchUtils.SearchNumUtils(context);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void initView(){
        keyView = (RecyclerView) contentView.findViewById(R.id.keys);
        initKeyLayout();
        call_btn = contentView.findViewById(R.id.call_btn);
        call_btn.setOnClickListener(this);
        numInput = (EditText) contentView.findViewById(R.id.input_et);
        backspace = contentView.findViewById(R.id.backspace);
        searchResultView = contentView.findViewById(R.id.search);

        initSearchResultsPopup();

        searchOneName = (TextView) contentView.findViewById(R.id.contact_name);
        searchOneNum = (TextView) contentView.findViewById(R.id.contact_num);

        backspace.setOnClickListener(this);
        searchResultView.setOnClickListener(this);
    }

    /**
     * 初始化播号盘list layout
     */
    private void initKeyLayout(){
        KeyGridAdapter adapter = new KeyGridAdapter(getContext(),keyView);
        keyView.setLayoutManager(new GridLayoutManager(getContext(),3));
        keyView.addItemDecoration(new CallItemDecoration(getContext(), CallItemDecoration.GRID,2, Color.WHITE));
        keyView.setAdapter(adapter);

        adapter.setKeyInputCallback(this);
    }

    /**
     * 初始化搜索列表弹窗view
     */
    private void initSearchResultsPopup(){
        searchList = new PopupWindow(getContext());

        search_list_view = (RecyclerView) LayoutInflater.from(getContext()).inflate(R.layout.search_result_list,null);
        searchList.setContentView(search_list_view);
        search_list_view.addItemDecoration(new CallItemDecoration(getContext(),LinearLayoutManager.HORIZONTAL,1,Color.WHITE));
        search_list_view.setLayoutManager(new LinearLayoutManager(getContext()));

        searchList.setOutsideTouchable(true);
    }

    @Override
    public void onKeyInput(String key) {
        int index = numInput.getSelectionStart();
        Editable edit = numInput.getEditableText();
        if(index<0 || index>edit.length()){
            edit.append(key);
        }else{
            edit.insert(index,key);
        }
        searchUtils.searchContacts(edit.toString(),this);
    }

    /**
     * 输入号码的回退处理方法
     */
    private void onInputBackspace(){
        int index = numInput.getSelectionStart();
        Editable edit = numInput.getEditableText();
        if(index<=0 || index>edit.length()){
            return;
        }else{
            edit.delete(index-1,index);
        }

        if(TextUtils.isEmpty(edit.toString())){
            visibleResult(false);
        }else{
            searchUtils.searchContacts(edit.toString(),this);
        }
    }

    /**
     * 显示或者隐藏搜索的匹配的第一个联系人view，在输入号码的view下面
     * @param visible
     */
    private void visibleResult(boolean visible){
        Transition transition = TransitionInflater.from(getContext()).inflateTransition(R.transition.data_loaded);
        TransitionManager.beginDelayedTransition((ViewGroup) contentView.findViewById(R.id.input_root),transition);
        if(visible){
            searchResultView.setVisibility(View.VISIBLE);
        }else {
            searchResultView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View view) {
        if(view == backspace){
            onInputBackspace();
        }else if(view == searchResultView){
            showResultsList();
        }else if(view == call_btn){
            onCallBtnClick();
        }
    }
    /**
     * 显示搜索的匹配联系人弹窗列表
     */
    private void showResultsList(){
        SearchNumAdapter searchNumAdapter = new SearchNumAdapter(getContext(),numInput.getText().toString(),searchNumResults);
        search_list_view.setAdapter(searchNumAdapter);
        searchNumAdapter.setItemClickCallback(this);
        searchList.setWidth(contentView.findViewById(R.id.num_input_layout).getWidth());
        searchList.setHeight(500);
        searchList.showAsDropDown(contentView.findViewById(R.id.num_input_layout));
    }

    private void onCallBtnClick(){
        String number = "";
        if(searchOneTop!=null){
            number = searchOneTop.getNumber();
        }else{
            number = numInput.getText().toString();
        }
        CallUtils.call(getContext(),number);
    }

    @Override
    public void onSearchResult(List<ContactSearchUtils.SearchNumResult> list) {
        if(list==null || list.size()==0){
            visibleResult(false);
            searchOneTop = null;
        }
        searchNumResults = list;
    }

    @Override
    public void onSearchOne(ContactSearchUtils.SearchNumResult searchNumResult) {
        searchOneTop = searchNumResult;
        ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
        SpannableString spannableString = new SpannableString(searchNumResult.getNumber());
        String highLightStr = numInput.getText().toString();

        int start = searchNumResult.getNumber().indexOf(highLightStr);
        int lenght = highLightStr.length();
        spannableString.setSpan(span,start,start+lenght, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        searchOneName.setText(searchNumResult.getName());
        searchOneNum.setText(spannableString);
        visibleResult(true);
    }

    @Override
    public void onItemClick(int postion, ContactSearchUtils.SearchNumResult searchNumResult) {
        if(searchNumResult!=null){
            CallUtils.call(getContext(),searchNumResult.getNumber());
        }
    }
}
